<template>
  <div id="app">
    <HeaderBar @addData="addData" />
    <ShowList :ItemList="ItemList" />
    <FooterBar @clearAllTodo="clearAllTodo" :ItemList="ItemList" />
  </div>
</template>

<script>
import HeaderBar from "./components/HeaderBar.vue";
import ShowList from "./components/ShowList.vue";
import FooterBar from "./components/FooterBar.vue";
import pubsub from "pubsub-js";

export default {
  name: "App",
  components: {
    HeaderBar,
    ShowList,
    FooterBar,
  },
  data() {
    return {
      ItemList: JSON.parse(localStorage.getItem("todos")) || [],
    };
  },
  methods: {
    addData(todoObj) {
      this.ItemList.unshift(todoObj);
      // console.log(this.ItemList);
    },
    checkTodo(_, id) {
      this.ItemList.forEach((item) => {
        if (item.id == id) {
          item.done = !item.done;
          // console.log(item.done)
        }
      });
    },
    updateTodo(id, value) {
      this.ItemList.forEach((item) => {
        if (item.id == id) {
          item.name = value;
        }
      });
    },
    deleteTodo(id) {
      this.ItemList = this.ItemList.filter((item) => item.id !== id);
    },
    checkAllTodo(value) {
      this.ItemList.forEach((item) => {
        item.done = value;
      });
    },
    clearAllTodo() {
      this.ItemList = this.ItemList.filter((item) => !item.done);
    },
  },
  watch: {
    ItemList: {
      deep: true,
      handler(value) {
        localStorage.setItem("todos", JSON.stringify(value));
      },
    },
  },
  mounted() {
    // this.$bus.$on("checkTodo", this.checkTodo);
    // 订阅消息
    this.pid = pubsub.subscribe("checkTodo", this.checkTodo);
    this.$bus.$on("deleteTodo", this.deleteTodo);
    this.$bus.$on("updateTodo", this.updateTodo);
    // console.log(this.$bus)
  },
  updated() {
    console.log("数据发生了改变");
  },
  beforeDestroy() {
    // this.$bus.$off("checkTodo");
    pubsub.unsubscribe(this.pid); // 取消订阅
    this.$bus.$off("deleteTodo");
    this.$bus.$off("updateTodo");
  },
};
</script>

<style lang="less">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  width: 500px;
  padding: 10px;
  border-radius: 3px;
  border: 1px solid rgb(228, 228, 228);
}
</style>
